package gui;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MyJFrame.java
 *
 * Created on Mar 17, 2010, 8:03:36 PM
 */
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.*;
import java.rmi.AccessException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import javax.swing.JOptionPane;

import replication.RegServer_Replication;
import rmi.Server;

import messagepasser.ClockFactory;
import messagepasser.ClockService;

import messagepasser.Message;
import messagepasser.MessagePasser;
import messagepasser.TimeStampedMessage;
import messagepasser.UserInfo;

/**
 *
 * @author keerthy
 */
public class LogIn extends javax.swing.JFrame {

	public boolean DEBUG = true;
	private MessagePasser passer;


	JOptionPane popUp;

	/** Creates new form MyJFrame */
	public LogIn(String configFileName) {
		ClockFactory factory = new ClockFactory();
		ClockService clock = factory.getInstance("Vector");

		//passer = new MessagePasser(configFileName,clock);
		initComponents();
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
	// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
	private void initComponents() {

		jButton1 = new javax.swing.JButton();
		jButton2 = new javax.swing.JButton();
		jLabel1 = new javax.swing.JLabel();
		jLabel4 = new javax.swing.JLabel();
		jLabel3 = new javax.swing.JLabel();
		jTextField3 = new javax.swing.JTextField();
		jPasswordField1 = new javax.swing.JPasswordField();
		jLabel2 = new javax.swing.JLabel();

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
		setBackground(new java.awt.Color(255, 255, 255));
		setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
		setResizable(false);

		jButton1.setBackground(new java.awt.Color(255, 255, 255));
		jButton1.setFont(new java.awt.Font("Verdana", 0, 10)); // NOI18N
		jButton1.setText("Login");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});

		jButton2.setBackground(new java.awt.Color(255, 255, 255));
		jButton2.setFont(new java.awt.Font("Verdana", 0, 10)); // NOI18N
		jButton2.setText("Register");
		jButton2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton2ActionPerformed(evt);
			}
		});

		jLabel1.setFont(new java.awt.Font("Vivaldi", 1, 48)); // NOI18N
		jLabel1.setText("TEC Box");

		jLabel4.setFont(new java.awt.Font("Verdana", 0, 10)); // NOI18N
		jLabel4.setText("password");

		jLabel3.setFont(new java.awt.Font("Verdana", 0, 10)); // NOI18N
		jLabel3.setText("email");

		jTextField3.setColumns(10);
		jTextField3.setFont(new java.awt.Font("Verdana", 0, 10)); // NOI18N
		jTextField3.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jTextField3ActionPerformed(evt);
			}
		});

		jPasswordField1.setColumns(10);
		jPasswordField1.setFont(new java.awt.Font("Verdana", 0, 10)); // NOI18N

		jLabel2.setIcon(new javax.swing.ImageIcon("C:\\Users\\Rishit\\Desktop\\18842\\images.jpg")); // NOI18N
		jLabel2.setText("jLabel2");
		jLabel2.setPreferredSize(new java.awt.Dimension(20, 20));

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
								.addGroup(layout.createSequentialGroup()
										.addGap(22, 22, 22)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
												.addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING)
												.addGroup(layout.createSequentialGroup()
														.addGap(10, 10, 10)
														.addComponent(jButton1))
														.addGroup(layout.createSequentialGroup()
																.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
																		.addComponent(jLabel3)
																		.addComponent(jLabel4))
																		.addGap(8, 8, 8)
																		.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
																				.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
																				.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)
																				.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
																				.addGroup(layout.createSequentialGroup()
																						.addContainerGap()
																						.addComponent(jLabel1)))
																						.addContainerGap(19, Short.MAX_VALUE))
		);
		layout.setVerticalGroup(
				layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(layout.createSequentialGroup()
						.addContainerGap()
						.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addGap(18, 18, 18)
						.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)
						.addGap(11, 11, 11)
						.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
								.addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
								.addComponent(jLabel3))
								.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
										.addComponent(jLabel4)
										.addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
										.addGap(10, 10, 10)
										.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE))
												.addGap(36, 36, 36))
		);

		pack();
	}// </editor-fold>//GEN-END:initComponents

	// Login
	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
		//read i/p user name
		String emailAddress;
		String password;
		UserInfo user = null;
		Server s = null;
		Registry registry = null;
		RegServer_Replication repl;
		repl = new RegServer_Replication();
		s = repl.getServer();
		
		if (s == null) {
			s = repl.getServer();
			if (s == null) {
				repl.shutDown();
			}
		}

		emailAddress = jTextField3.getText().trim();
		password = jPasswordField1.getText();

		//Email address validation checks
		if (emailAddress == null || emailAddress.length() == 0) {
			popUp = new JOptionPane();
			popUp.showMessageDialog(null,
					"Enter Email address",
					"Inane error",
					JOptionPane.ERROR_MESSAGE);
			return;

		} else if (!emailAddress.contains("@") || emailAddress.contains("/")) {
			popUp = new JOptionPane();
			popUp.showMessageDialog(null,
					"Enter valid Email address",
					"Inane error",
					JOptionPane.ERROR_MESSAGE);
			jTextField3.setText(" ");

			return;

		} else if (emailAddress.startsWith("@") || emailAddress.endsWith("@")) {
			popUp = new JOptionPane();
			popUp.showMessageDialog(null,
					"Enter valid Email address",
					"Inane error",
					JOptionPane.ERROR_MESSAGE);
			jTextField3.setText(" ");
			return;
		}


		if (password == null || password.length() == 0) {
			popUp = new JOptionPane();
			popUp.showMessageDialog(null,
					"Enter Valid Password",
					"Inane error",
					JOptionPane.ERROR_MESSAGE);
			jPasswordField1.setText(" ");
			return;
		}

		System.out.println("Login Button Pressed");
		InetAddress addr = null;
		try { 
			addr = InetAddress.getLocalHost(); // Get IP Address 
		} catch (UnknownHostException e) { } 

		int port = 6666;
		if (emailAddress.contains("asd")) {
			port = 7777;
		}
		else if (emailAddress.contains("rishit")){
			port = 6665;
		}
		else {
			port = 6666;
		}

		try {
			user = s.login(emailAddress, password, addr.getHostAddress().toString(), port);
		}
		catch (Exception e) {
			try {
				
				s = repl.getServer();
				user = s.login(emailAddress, password, addr.getHostAddress().toString(), port);
			}
			catch (Exception e1) {
				e.printStackTrace();
				repl.shutDown();
			}
		}

		if (user == null) {
			popUp.showMessageDialog(null,
					"Wrong user name or password :(",
					"Validation Error",
					JOptionPane.ERROR_MESSAGE);
			jPasswordField1.setText(" ");
			return;
		}



		System.out.println("Sent Login Message");

		//TODO: Check for correct password and Email if ther in DB or nt and if not display proper error message;

		if (DEBUG) {
			System.out.println("\n" + emailAddress);
			System.out.println("\n" + password);
		}


		this.setVisible(false);    
		new MainWindow(user, s, repl).setVisible(true);
	}//GEN-LAST:event_jButton1ActionPerformed

	// Registeration
	private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
		Server s = null;
		Registry registry = null;
		try {
			registry = LocateRegistry.getRegistry("169.254.122.143");
			System.out.println ("lookup successful");
			System.out.println (registry.list()[0] + " " + registry.REGISTRY_PORT);;
			try {
				s = (Server) registry.lookup("TecBox_PrimaryServer");
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				System.out.println ("Primary down");
				try {
					s = (Server) registry.lookup("TecBox_BackupServer");
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println ("Cannot find any Servers");
					System.exit(1);
				}

			} 

		} catch (RemoteException e2) {
			// TODO Auto-generated catch block
			System.out.println ("Cannot find registry return");
			System.exit(1);
		}
		this.setVisible(false);
		Registration reg = new Registration(s);
		reg.setVisible(true);

		if (DEBUG) {
			System.out.println("register clicked");
		}
	}//GEN-LAST:event_jButton2ActionPerformed

	private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField3ActionPerformed
		// TODO add your handling code here:
	}//GEN-LAST:event_jTextField3ActionPerformed

	/**
	 * @param args the command line arguments
	 */
	public static void main(String args[]) {
		final String fileName = "";
		java.awt.EventQueue.invokeLater(new Runnable() {

			public void run() {
				new LogIn(fileName).setVisible(true);
			}
		});
	}
	// Variables declaration - do not modify//GEN-BEGIN:variables
	private javax.swing.JButton jButton1;
	private javax.swing.JButton jButton2;
	private javax.swing.JLabel jLabel1;
	private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JPasswordField jPasswordField1;
	private javax.swing.JTextField jTextField3;
	// End of variables declaration//GEN-END:variables
}
